package com.oa.erp.ass.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.erp.ass.entity.AssetCard;
import com.oa.erp.ass.entity.AssetCardOper;
import com.oa.erp.ass.service.AssetCardOperService;
import com.oa.erp.ass.service.AssetCardService;
import com.oa.erp.pur.entity.StockIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/erp/ass/assetCard")
@Api(tags = {"ass_asset_card-操作接口"})
public class AssetCardController {

    static Logger logger = LoggerFactory.getLogger(AssetCardController.class);


    @Autowired
    private AssetCardService assetCardService;

    @Autowired
    private AssetCardOperService assetCardOperService;

    @ApiOperation(value = "ass_asset_card-查询列表", notes = " ")
    @ApiEntityParams(AssetCard.class)
    @ApiResponses({@ApiResponse(code = 200, response = AssetCard.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listAssetCard(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "cardIds");
        RequestUtils.transformArray(params, "categoryIds");
        RequestUtils.transformArray(params, "cbCenterIds");
        RequestUtils.transformArray(params, "useDeptids");
        QueryWrapper<AssetCard> qw = QueryTools.initQueryWrapper(AssetCard.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = assetCardService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @RequestMapping(value = "/getAssetCards", method = RequestMethod.GET)
    public Result getAssetCards(@RequestParam Map<String, Object> assetCard) {
        return Result.ok().setData(listAssetCard(assetCard));
    }

    @RequestMapping(value = "/getInventoryCards", method = RequestMethod.GET)
    public Result getInventoryCards(@RequestParam Map<String, Object> assetCard) {
        User user = LoginUtils.getCurrentUserInfo();
        assetCard.put("branchId", user.getBranchId());
        RequestUtils.transformArray(assetCard, "ids");
        List<Map<String, Object>> assetDetailList = assetCardService.getInventoryCards(assetCard);    //列出AssetDetail列表

        return Result.ok("query-ok", "查询成功").setData(assetDetailList);
    }

    @ApiOperation(value = "查询资产编码是否重复", notes = "查询资产编码是否重复")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/isExitAssetSn", method = RequestMethod.GET)
    public Result isExitAssetSn(@RequestParam String assetSn) {

        User user = LoginUtils.getCurrentUserInfo();
        AssetCard assetCard = new AssetCard();
        assetCard.setBranchId(user.getBranchId());
        assetCard.setAssetSn(assetSn);
        if (assetCardService.countByWhere(assetCard) > 0) {
            return Result.error("编号重复，请修改编号再提交");
        }
        return Result.ok();
    }

    @ApiOperation(value = "ass_asset_card-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCard.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addAssetCard(@RequestBody AssetCard assetCard) {
        if (StringUtils.isEmpty(assetCard.getCardId())) {
            assetCard.setCardId(assetCardService.createKey("cardId"));
        } else {
            AssetCard assetCardQuery = new AssetCard(assetCard.getCardId());
            if (assetCardService.countByWhere(assetCardQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        assetCardService.insertAssetCard(assetCard);
        return Result.ok("add-ok", "添加成功！").setData(assetCard);
    }

    @ApiOperation(value = "创建资产编码", notes = "查询资产编码是否重复")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/createAssetSn", method = RequestMethod.POST)
    public Result createAssetSn(@RequestBody AssetCard assetCard) {
        User user = LoginUtils.getCurrentUserInfo();
        if (!StringUtils.hasText(assetCard.getPassetSn())) {
            return Result.error("passetSn-0", "上级资产编码不能为空");
        }
        String assetSn = this.assetCardService.createAssetSn(assetCard.getPassetSn(), user.getBranchId());
        return Result.ok().setData(assetSn).setData(assetSn);
    }

    @ApiOperation(value = "ass_asset_card-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delAssetCard(@RequestBody AssetCard assetCard) {
        if (!StringUtils.hasText(assetCard.getCardId())) {
            return Result.error("pk-not-exists", "请上送主键参数id");
        }
        AssetCard assetCardDb = assetCardService.selectOneObject(assetCard);
        if (assetCardDb == null) {
            return Result.error("data-not-exists", "数据不存在，无法删除");
        }
        if (!"0".equals(assetCardDb.getCardStatus()) && !"4".equals(assetCardDb.getCardStatus())) {
            return Result.error("status-not-0|4", "当前资产不是闲置、报废状态，无法删除");
        }
        AssetCardOper oper = new AssetCardOper();
        oper.setCardId(assetCardDb.getCardId());
        oper.setBizFlowState("1");
        long operNum = assetCardOperService.countByWhere(oper);
        if (operNum > 0) {
            return Result.error("bizFlowState-1", "当前资产有" + operNum + "个正在执行的审批流，不能删除");
        }
        assetCardService.deleteByPk(assetCard);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "ass_asset_card-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCard.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editAssetCard(@RequestBody AssetCard assetCard) {
        assetCardService.updateAssetCard(assetCard);
        return Result.ok("edit-ok", "修改成功！").setData(assetCard);
    }

    @ApiOperation(value = "批量更新资产卡片", notes = "批量更新资产卡片")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchEditAssetCard", method = RequestMethod.POST)
    public Result batchEditAssetCard(@RequestBody Map<String, Object> assetCard) {
        assetCardService.batchEditAssetCard(assetCard);
        return Result.ok();
    }

    //上传的excel文件
    @PostMapping("/importAssetCard")
    public Result addSubject(MultipartFile file) {
        try {
            assetCardService.importAssetCard(file, assetCardService);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return Result.ok();
    }


    @ApiOperation(value = "ass_asset_card-批量修改某些字段", notes = "")
    @ApiEntityParams(value = AssetCard.class, props = {}, remark = "ass_asset_card", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCard.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        assetCardService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "ass_asset_card-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelAssetCard(@RequestBody List<AssetCard> assetCards) {
        User user = LoginUtils.getCurrentUserInfo();
        if (assetCards.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<AssetCard> datasDb = assetCardService.listByIds(assetCards.stream().map(i -> i.getCardId()).collect(Collectors.toList()));

        List<AssetCard> no = new ArrayList<>();
        List<AssetCard> can = new ArrayList<>(datasDb);
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            assetCardService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }
        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getCardId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "ass_asset_card-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCard.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(AssetCard assetCard) {
        AssetCard data = (AssetCard) assetCardService.getById(assetCard);
        return Result.ok().setData(data);
    }

}
